package com.bidevalution.support.face;

import lombok.extern.log4j.Log4j2;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * SHA1 class
 *
 * 第三方应用发到平台的消息签名接口.
 */
@Log4j2
public class SHA1 {
	/**
	 * 用SHA1算法生成安全签名
	 * @param appId 应用Id
	 * @param appId 应用Key
	 * @param timestamp 时间戳
	 * @param nonce 随机字符串
	 * @param requestId 请求流水
	 * @param data json请求数据
	 * @return 安全签名
	 */
	public static String getSHA1(String appId, String appKey, String timestamp, String nonce,String requestId, String data){
		try {
			String[] array = new String[] { appId, appKey, timestamp, nonce, requestId, data };
			StringBuffer sb = new StringBuffer();
			// 字符串排序
			Arrays.sort(array);
			for (int i = 0; i < 6; i++) {
				sb.append(array[i]);
			}
			String str = sb.toString();
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
            log.error(e.getMessage(), e);
		}
		return null;
	}
}
